import { FileExcelOutlined } from '@ant-design/icons';
import { Button, message, Steps, theme } from 'antd';
import { useState } from 'react';
import getFileNameFromPath from '../../../util/getFileNameFromPath';
import ComponmentTypeList from './componmentTypeList';
import UploadFile from './uploadFile';
const TableImport = () => {
  let { token } = theme.useToken();
  //进度条当前节点
  let [current, setCurrent] = useState(0);
  //上传文件返回的信息
  let [uploadInfo, setUploadInfo] = useState({});
  //是否上传完成
  let [uploaded, setUploaded] = useState(false);
  //下载文件路径
  let [outputFilePathList, setOutputFilePathList] = useState([]);

  /*
        步骤2提交
    */
  const submitTableType = () => {
    let { tenantId, excelFileName, tablesElements } = uploadInfo;
    let body = {
      tenantId,
      excelFileName,
      tablesElements,
    };
    fetch(API_URL + '/importTable/submitTableType', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json', // 设置 Content-Type 为 JSON
      },
      body: JSON.stringify(body),
    })
      .then((res) => res.json())
      .then((e) => {
        let { success } = e;
        if (success) {
          let { outputFilePathList } = e;
          if (outputFilePathList) {
            message.success('文件生成成功！');
            setOutputFilePathList(outputFilePathList);
            next();
          }
        } else {
          let errMsg = '存在选项组件未填写信息，请确认后重新提交！\n';
          let { errInfo } = e;
          const content = (
            <div>
              {errMsg}
              {errInfo.map((err, index) => (
                <div key={index}>{err}</div>
              ))}
            </div>
          );

          message.error({
            content,
            duration: 3,
          });
        }
      })
      .catch((e) => {
        message.error('提交错误！错误:' + e);
      })
      .finally(() => {});
  };

  /*
       下载按钮
   */
  const handleDownload = (outputFilePath) => {
    // 发送文件名给后端并下载文件
    fetch(API_URL + '/importTable/download', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: outputFilePath,
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('请求失败');
        }
        return response.blob();
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = getFileNameFromPath(outputFilePath); // 下载文件的名称
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      })
      .catch((error) => message.error('文件下载失败:', error));
  };

  /*
        进度条控件
    */
  const next = () => {
    setUploaded(false);
    setCurrent(current + 1);
  };
  const prev = () => {
    setUploaded(false);
    setCurrent(current - 1);
  };
  //样式
  const contentStyle = {
    lineHeight: '260px',
    textAlign: 'center',
    color: token.colorTextTertiary,
    backgroundColor: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    border: `1px dashed ${token.colorBorder}`,
    marginTop: 16,
  };

  //进度条节点
  const steps = [
    {
      title: '录入信息',
      content: (
        <div>
          <UploadFile setUploadInfo={setUploadInfo} setUploaded={setUploaded} />
        </div>
      ),
    },
    {
      title: '设置组件信息',
      content: (
        <div>
          <ComponmentTypeList
            setUploadInfo={setUploadInfo}
            uploadInfo={uploadInfo}
            setCurrent={setCurrent}
          />
        </div>
      ),
    },
    {
      title: '下载dat文件',
      content: (
        <div>
          {/* <Button type="primary" onClick={handleDownload}>下载文件</Button> */}
          {outputFilePathList.map((e, index) => (
            <div>
              <Button
                key={index}
                onClick={() => {
                  handleDownload(e);
                }}
              >
                <FileExcelOutlined />
                {getFileNameFromPath(e)}
              </Button>
            </div>
          ))}
        </div>
      ),
    },
  ];
  const items = steps.map((item) => ({
    key: item.title,
    title: item.title,
  }));

  return (
    <>
      <Steps current={current} items={items} />
      <div style={contentStyle}>{steps[current].content}</div>
      <div
        style={{
          marginTop: 24,
        }}
      >
        {current === 0 && uploaded && (
          <Button type="primary" onClick={() => next()}>
            下一步
          </Button>
        )}
        {current === 1 && (
          <Button
            style={{
              margin: '0 8px',
            }}
            onClick={() => prev()}
          >
            上一步
          </Button>
        )}

        {current === 1 && (
          // && current != 0
          <Button type="primary" onClick={submitTableType}>
            提交
          </Button>
        )}

        {current === 2 && (
          // && current != 0
          <Button
            type="primary"
            onClick={() => {
              setCurrent(0);
              setUploadInfo({});
              setUploaded(false);
              setOutputFilePathList([]);
            }}
          >
            重新录入
          </Button>
        )}
      </div>
    </>
  );
};

export default TableImport;
